#include "in.h"

int LoadAllMessageStores( struct MQBroker *broker )
{
	DIR			*dp = NULL ;
	struct dirent		*dtp = NULL ;
	char			store_path_name[ PATH_MAX ] ;
	struct stat		dir_stat ;
	struct MQStore	*store = NULL ;
	
	int			nret = 0 ;
	
	dp = opendir( broker->data_path ) ;
	if( dp == NULL )
	{
		ERRORLOG( "opendir[%s] failed , errno[%d]" , broker->data_path , errno );
		return -1;
	}
	else
	{
		DEBUGLOG( "opendir[%s] ok" , broker->data_path );
	}
	
	for( ; ; )
	{
		dtp = readdir( dp ) ;
		if( dtp == NULL )
			break;
		
		if( STRCMP( dtp->d_name , == , "." ) || STRCMP( dtp->d_name , == , ".." ) )
			continue;
		
		memset( store_path_name , 0x00 , sizeof(store_path_name) );
		snprintf( store_path_name , sizeof(store_path_name) , "%s/%s" , broker->data_path , dtp->d_name );
		stat( store_path_name , & dir_stat );
		if( ! S_ISDIR(dir_stat.st_mode) )
			continue;
		
		store = (struct MQStore *)malloc( sizeof(struct MQStore) ) ;
		if( store == NULL )
		{
			ERRORLOG( "malloc MQStore failed , errno[%d]" , errno )
			return -2;
		}
		memset( store , 0x00 , sizeof(struct MQStore) );
		
		strcpy( store->store_name , dtp->d_name );
		store->store_name_len = strlen(store->store_name) ;
		snprintf( store->store_path , sizeof(store->store_path)-1 , "%s/%s" , broker->data_path , dtp->d_name );
		INIT_LIST_HEAD( & (store->msg_file_list) );
		INIT_LIST_HEAD( & (store->delay_msg_file_list) );
		
		nret = LoadAllMessageDataFiles( broker , store ) ;
		if( nret )
		{
			ERRORLOG( "LoadAllMessageStoreDataFiles failed , errno[%d]" , errno )
			return -3;
		}
		else
		{
			INFOLOG( "LoadAllMessageStoreDataFiles ok" )
		}
		
		nret = LoadAllTopics( broker , store ) ;
		if( nret )
		{
			ERRORLOG( "LoadAllTopics failed[%d] , errno[%d]" , errno )
			return -3;
		}
		else
		{
			INFOLOG( "LoadAllTopics ok" )
		}
		
		nret = LoadAllDelayMessageDataFiles( broker , store ) ;
		if( nret )
		{
			ERRORLOG( "LoadAllDelayMessageStoreDataFiles failed , errno[%d]" , errno )
			return -4;
		}
		else
		{
			INFOLOG( "LoadAllDelayMessageStoreDataFiles ok" )
		}
		
		INFOLOG( "add[%.*s] to store_name_tree" , store->store_name_len,store->store_name )
		LinkStoreNameTreeNode( broker , store );
	}
	
	closedir( dp );
	
	return 0;
}

int UnloadAllMessageStores( struct MQBroker *broker )
{
	struct MQStore	*store = NULL ;
	
	store = NULL ;
	for( ; ; )
	{
		store = TravelStoreNameTreeNode( broker , store ) ;
		if( store == NULL )
			break;
		
		UnloadAllMessageDataFiles( broker , store );
		store->max_msg_offset = 0 ;
		
		UnloadAllTopics( broker , store );
		
		UnloadAllDelayMessageDataFiles( broker , store );
		store->max_delay_msg_offset = 0 ;
		DestroyDelayMessageOffsetTree( store );
	}
	
	DestroyStoreNameTree( broker );
	
	return 0;
}

